<template>
  <div>
    <el-form ref="newsFirst" :model="newsFirst" label-width="80px">
      <el-form-item label="新闻首页图片">
        <el-upload
          :action="BASE_API+'/upload/file'"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload">
          <img v-if="image!=null" :src="newsFirst.imageUrl" class="avatar" width="300px" height="200px">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="新闻首页标题">
        <el-input v-model="newsFirst.title" style="width:600px"/>
      </el-form-item>
      <el-form-item label="新闻首页描述">
        <textarea v-model="newsFirst.description" style="width:600px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">修改</el-button>
        <el-button @click="oncancel()">取消</el-button>
      </el-form-item>
      </el-form>
  </div>
</template>
<script>
import news from '@/api/smart/news'
export default {
  data(){
    return{
      newsFirst: {
        description:'',
        imageUrl:'',
        title:''
      },
      image:'',
      BASE_API: process.env.BASE_API, // 接口API地址
    }
  },
  created() {
    this.selectNewsFirstImage()
  },
  methods:{
    selectNewsFirstImage(){
      news.selectNewsFirstImage().then(response=>{
        this.newsFirst=response.data.data
        console.log(this.newsFirst)
      })
    },
    handleSuccess(res, file) {
      // console.log(res)// 上传响应
      // console.log(URL.createObjectURL(file.raw))// base64编码
      this.newsFirst.imageUrl = res.data.url
      this.image=file.url
      console.log(this.image)
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG或 PNG 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return (isJPG || isPNG) && isLt10M
    },
    onSubmit(){
      news.updateNewsFirstImage(this.newsFirst).then(response=>{
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        this.$router.push({ path: '/news/list' })
      })


    },
    oncancel(){
        this.$router.push({ path: '/news/list' })
      },


  }
}

</script>
